// fileHandler形式大数据量循环 耗时10S
// const fs = require('node:fs/promises');
// (async()=>{
//     console.time('a');
//     const fileHandler = await fs.open('./test.txt', 'w');
//     for ( let i = 0; i < 1000000; i++){
//         await fileHandler.write(` ${i} `);
//     }
// })()

// fs同步形式 耗时1.3S
// const fs = require('node:fs');
// (async()=>{
//     console.time('a');
//     fs.open('./test.txt', 'w', (err, fd)=>{
//         console.log(fd);
//         for(let i =0; i < 1000000; i++){
//             const buffer = Buffer.from(` ${i} `, 'utf-8');
//             fs.writeSync(fd, buffer);
//         }
//         console.timeEnd('a');
//     })
// })()

// streams形式大数据量循环 耗时10S
const fs = require('node:fs/promises');
(async()=>{
    console.time('a');
    const fileHandler = await fs.open('./test.txt', 'w');
    const stream = fileHandler.createWriteStream();

    let i = 0;
    const writeLargeFile = ()=>{
        while ( i < 1000000 ) {
            const buff = Buffer.from(` ${i} `, 'utf-8');
            if ( i === 999999 ) {
                console.log(stream);
                return stream.end(buff);
            }
            if ( !stream.write(buff)){
                break;
            }
            i++;
        }
    }
    writeLargeFile();
    stream.on('drain', ()=>{
        console.log(stream.writableLength);
        console.log('----------');
        console.log(stream.writableHighWaterMark);
        writeLargeFile();
    })
    stream.on('finish',  ()=>{
        console.timeEnd('a');
        fileHandler.close();
    })
   
})()